import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import routes from './routers'
import Util from '@/utils'
import Storage from '@/utils/storage'
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

Vue.use(Router)

const router = new Router({
  routes,
  mode: 'history',
  linkActiveClass: 'active',
})

const LOGIN_PAGE_NAME = 'login'

router.beforeEach((to, from, next) => {
  NProgress.start();
  // 需要
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 初始化数据
    Storage.defaults({
      'user': {}
    })
    const user = Storage.get('user')
    if (user.name) {
      store.commit('setAvator', user.avator)
      store.commit('setUserName', user.name)
      store.commit('setUserId', user.id)
    } else {
      store.dispatch('getUserInfo')
    }
    if (Util.getToken()) {
      store.commit('setToken', Util.getToken())
    }
    // 判断登录
    const token = Util.getToken()
    if (!token && to.name !== LOGIN_PAGE_NAME) {
      // 未登录且要跳转的页面不是登录页
      next({
        name: LOGIN_PAGE_NAME // 跳转到登录页
      })
    } else if (!token && to.name === LOGIN_PAGE_NAME) {
      // 未登陆且要跳转的页面是登录页
      next() // 跳转
    } else if (token && to.name === LOGIN_PAGE_NAME) {
      // 已登录且要跳转的页面是登录页
      Util.markTitle()
      next({
        path: '/admin' // 跳转到 /页
      })
    } else {
      next()
    }
  } else {
    next()
  }
})
router.afterEach((to, from) => {
  // ...
  NProgress.done();
});

export default router
